package com.zheng.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zheng.common.Result;
import com.zheng.entity.User;
import com.zheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.sql.Wrapper;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //PostMapping进行插入操作
    @PostMapping
    public Result<?> save(@RequestBody User user){
        System.out.println(user);
        if(user.getPassword()==null){
            user.setPassword("123456");
        }
        userService.save(user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        QueryWrapper<User> wrapper =new QueryWrapper();
        wrapper.eq("username",user.getUsername()).eq("password",user.getPassword());
        User res = userService.getOne(wrapper);
        if(res ==null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success(res);
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
        //判断用户名是否存在，存在则说明用户已存在
        QueryWrapper<User> wrapper =new QueryWrapper();
        wrapper.eq("username",user.getUsername());
        User res = userService.getOne(wrapper);
        if(res!=null){
            return Result.error("-1","用户名已存在");
        }
         userService.save(user);
        return Result.success();
    }
    //PutMapping用来更新数据
    @PutMapping
    public Result<?> updateUser(@RequestBody User user){


        userService.updateById(user);
        return Result.success();
    }
    @DeleteMapping("/{id}")
    //@PathVariable 获取路径传过来的id
    public Result<?> DeleteUser(@PathVariable Long id){

        userService.removeById(id);
        return Result.success();
    }

    //GetMapping进行查询操作
    @GetMapping
    //第一个参数当前页，当个参数每页个数，第三个参数模糊查询的条件
    //每页五条数据，第三页的第二条数据
    public Result<?> selectAll(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String search,@RequestParam String option){


        //对user进行分页 page分页需要两个参数pageNum, pageSize
        Page<User> page = new Page<>(pageNum, pageSize);
        //创建QueryWrapper进行过条件查询分页
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        //如果字段的值不为空进行模糊查询  空！=null
        //用到了hutool工具类StrUtil 可以去官网进行查看hutool.cn
        if(StrUtil.isNotBlank(search)){
            queryWrapper.like(option,search);
        }
        Page<User> userPage = userService.page(page,queryWrapper);
        return Result.success(userPage);
    }
}
